﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iBookstore.Models;

namespace iBookstore.Controllers
{
    [Authorize]
    public class CheckoutController : Controller
    {
        iBookstoreEntities storeDB = new iBookstoreEntities();
        const string PromoCode = "FREE";

        //
        // GET: /Checkout/
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Checkout/AddressAndPayment
        public ActionResult AddressAndPayment()
        {
            return View();
        }

        //
        // POST: /Checkout/AddressAndPayment
        [HttpPost]
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();
            TryUpdateModel(order);

            try
            {
                if (string.Equals(values["PromoCode"], PromoCode, StringComparison.OrdinalIgnoreCase) == false)
                {
                    ViewBag.Message = "Don't forget the PromoCode";
                    return View(order);
                }
                else if (!AllIsInStock(ShoppingCart.GetCart(this.HttpContext)))
                {
                    ViewBag.Message = "Sorry but one or more of the products in your cart is not in stock";
                    return View(order);
                } else
                {
                    order.Username = User.Identity.Name;
                    order.OrderDate = DateTime.Now;

                    //Save Order
                    storeDB.Orders.Add(order);
                    storeDB.SaveChanges();

                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    UpdateStock(cart);
                    cart.CreateOrder(order);

                    return RedirectToAction("Complete", new { id = order.OrderId });
                }
            }
            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }

        private bool AllIsInStock(ShoppingCart shoppingCart)
        {
            List<Cart> carts = shoppingCart.GetCartItems();

            foreach (Cart cart in carts)
            {
                if (storeDB.Books.Find(cart.BookId).Quantity - cart.Count < 0)
                {
                    return false;
                }
            }

            return true;
        }

        private void UpdateStock(ShoppingCart shoppingCart)
        {
            List<Cart> carts = shoppingCart.GetCartItems();

            foreach(Cart cart in carts) {
                storeDB.Books.Find(cart.BookId).Quantity -= cart.Count;
                storeDB.SaveChanges();
            }

            return;
        }

        //
        // GET: /Checkout/Complete
        public ActionResult Complete(int id)
        {
            // Validate customer owns this order
            bool isValid = storeDB.Orders.Any(
                o => o.OrderId == id &&
                o.Username == User.Identity.Name);

            if (isValid)
            {
                return View(id);
            }
            else
            {
                return View("Error");
            }
        }
    }
}
